﻿using System.Windows;
using System.Windows.Media;

namespace DynamicMVVM.Demo.UI.Utilities
{
    public class AutoFrameworkElementScaler
    {
        #region Internal fields

        private readonly FrameworkElement _fe;
        private readonly FrameworkElement _parentElement;
        private Size _orgSize;
        private Size _previousSize;

        #endregion

        #region Construction

        /// <summary>
        /// Creates a new auto-scaler class.
        /// </summary>
        /// <param name="referenceSize">Size to use as a basis for further scaling.</param>
        /// <param name="fe"></param>
        /// <param name="parentElement"></param>
        public AutoFrameworkElementScaler(Size referenceSize, FrameworkElement fe, FrameworkElement parentElement)
        {
            _fe = fe;
            _parentElement = parentElement;

            var st = new ScaleTransform(1.0, 1.0, 0, 0);
            _fe.LayoutTransform = st;
            _previousSize = _orgSize = referenceSize;
            _parentElement.SizeChanged += ParentElementSizeChanged;
        }

        #endregion

        #region Event handlers

        void ParentElementSizeChanged(object sender, SizeChangedEventArgs e)
        {
            var scaleObject = _fe.LayoutTransform as ScaleTransform;

            if (scaleObject != null)
            {
                var prevSize = _previousSize;
                var newSize = e.NewSize;

                //Console.WriteLine("Prev: {0}, New: {1}", prevSize, newSize);
                if ((prevSize.Width > 0) && (prevSize.Height > 0))
                {
                    var scaleX = newSize.Width / _orgSize.Width;
                    var scaleY = newSize.Height / _orgSize.Height;
                    _fe.BeginInit();
                    scaleObject.ScaleX = scaleX;
                    scaleObject.ScaleY = scaleY;
                    _fe.EndInit();
                }
                else
                {
                    _orgSize = newSize;
                }
            }
            _previousSize = e.NewSize;
        }

        #endregion
    }
}
